package be.novelfaces.component.numpaddecseparator;

import java.io.IOException;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;

public class NumpadDecimalSeparatorRenderer extends Renderer {
	
	@Override
	public void encodeBegin(FacesContext context, UIComponent component)
			throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("span", null);
		writer.writeAttribute("id", component.getClientId(), null);
	}
	
	@Override
	public void encodeEnd(FacesContext context, UIComponent component)
			throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("script", null);
		writer.writeAttribute("type", "text/javascript", null);
		writer.write("new NovelFaces.numpadDecSeparator('" + component.getClientId() + "', {");
		writer.write("separator:'" + getSeparator(context) + "'");
		writer.write("});");
		writer.endElement("script");
		writer.endElement("span");
	}
	
	@Override
	public boolean getRendersChildren() {
		return true;
	}
	
	private String getSeparator(FacesContext context) {
		Locale locale = context.getViewRoot().getLocale();
		return String.valueOf(DecimalFormatSymbols.getInstance(locale).getDecimalSeparator());
	}

}
